import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/values/colors.dart';
import 'package:sainbainu/common/widgets/cancel_confirm_wrapper.dart';

class UniqueNoDialog extends StatefulWidget {
  final String? value;
  final VoidCallback? onCancelTap;
  final void Function(String value)? onConfirmTap;

  const UniqueNoDialog({
    super.key,
    this.value,
    this.onCancelTap,
    this.onConfirmTap,
  });

  @override
  State<UniqueNoDialog> createState() => _UniqueNoDialogState();
}

class _UniqueNoDialogState extends State<UniqueNoDialog> {
  String? _value;

  @override
  void initState() {
    super.initState();
    _value = widget.value;
  }

  /// 点击确认
  void handleConfirm() {
    if (_value == null || _value!.isEmpty) {
      return LoadingUtil.showInfo('SNID 不能为空');
    }
    // 长度为5到16个字符，只允许包含字母、数字和下划线，其字母开头
    final regex = RegExp(r'^[a-zA-Z][a-zA-Z0-9_]{4,15}$');
    // 使用正则表达式匹配输入
    if (!regex.hasMatch(_value!)) {
      return LoadingUtil.showInfo('SNID 格式不正确');
    }
    if (widget.onConfirmTap != null) {
      widget.onConfirmTap!(_value!);
    }
  }

  /// 收集输入内容
  void onChanged(String value) {
    _value = value;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return CancelConfirmWrapper(
      titleText: '${'设置'.tr} SNID',
      onCancelTap: widget.onCancelTap,
      onConfirmTap: _value == widget.value ? null : handleConfirm,
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          children: [
            customTextField(),
          ],
        ),
      ),
    );
  }

  /// 自定义输入框
  Widget customTextField() {
    return TextFormField(
      initialValue: _value,
      keyboardType: TextInputType.text,
      maxLength: 16,
      maxLines: 1,
      cursorColor: AppColors.primary,
      decoration: InputDecoration(
        hintText: '唯一号，请谨慎输入'.tr,
        helperText: '5-16个字符，字母开头，只允许包含字母、数字、下划线'.tr,
        helperStyle: const TextStyle(
          color: AppColors.unactive,
        ),
        focusedBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.primary),
        ),
        enabledBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.border),
        ),
        errorText: null,
      ),
      onChanged: onChanged,
    );
  }
}
